package com.carleasoft.mps.cms.business.train.service.Impl;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carleasoft.mps.cms.business.clerk.bean.DealDataEntity;
import com.carleasoft.mps.cms.business.clerk.bean.DealProcessNodeEntity;
import com.carleasoft.mps.cms.business.clerk.service.DealDataService;
import com.carleasoft.mps.cms.business.clerk.service.DealProcessNodeService;
import com.carleasoft.mps.cms.business.message.bean.entity.MessageReceive;
import com.carleasoft.mps.cms.business.message.dao.MessageNoteMapper;
import com.carleasoft.mps.cms.business.message.service.MessageReceiveService;
import com.carleasoft.mps.cms.business.repairs.dao.RepairsMessageMapper;
import com.carleasoft.mps.cms.business.train.bean.entity.*;
import com.carleasoft.mps.cms.business.train.bean.po.*;
import com.carleasoft.mps.cms.business.train.bean.vo.*;
import com.carleasoft.mps.cms.business.train.constants.ExceptionTrainEnum;
import com.carleasoft.mps.cms.business.train.dao.TrainExamMapper;
import com.carleasoft.mps.cms.business.train.dao.TrainPlanMapper;
import com.carleasoft.mps.cms.business.train.service.*;
import com.carleasoft.mps.cms.business.write.bean.entity.LeadingCadreEntity;
import com.carleasoft.mps.cms.business.write.service.LeadingCadreService;
import com.carleasoft.mps.cms.utils.ObjectSelfUtil;
import com.carleasoft.mps.core.exceptions.BusinessException;
import com.carleasoft.mps.core.user.ThreadUserContext;
import com.carleasoft.mps.core.user.UserCacheData;
import com.carleasoft.mps.core.utils.IBeanUtil;
import com.carleasoft.mps.excel.utils.ConvertTemplatePath;
import com.carleasoft.mps.excel.utils.ExcelUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 训练计划主题表 服务实现类
 * </p>
 *
 * @author fan
 * @since 2023-05-17
 */
@Service
public class TrainPlanServiceImpl extends ServiceImpl<TrainPlanMapper, TrainPlan> implements TrainPlanService {

    @Autowired
    private TrainPlanActivityService trainPlanActivityService;
    @Autowired
    private TrainPlanEducationService trainPlanEducationService;
    @Autowired
    private TrainPlanItemService trainPlanItemService;
    @Autowired
    private TrainPlanStageService trainPlanStageService;
    @Autowired
    private TrainPlanTeachService trainPlanTeachService;
    @Autowired
    private MessageNoteMapper messageNoteMapper;
    @Autowired
    private RepairsMessageMapper repairsMessageMapper;
    @Autowired
    private TrainExamMapper trainExamMapper;
    @Autowired
    private TrainScoreService trainScoreService;
    @Autowired
    private DealDataService dealDataService;
    @Autowired
    private DealProcessNodeService dealProcessNodeService;
    @Autowired
    private LeadingCadreService leadingCadreService;
    @Autowired
    private MessageReceiveService messageReceiveService;
    @Autowired
    private TrainScoreContentService trainScoreContentService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(TrainPlanAddOrEditPo trainPlanAddOrEditPo) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
//        List<TrainPlanItem> trainPlanItems = new LinkedList<>();
//        List<TrainClass> trainClass = trainPlanAddOrEditPo.getTrainClass();
//        List<TrainPlan> trainPlans = new LinkedList<>();
//        if (CollUtil.isNotEmpty(trainClass)) {
//            trainClass.stream().forEach(a -> {
//                TrainPlan trainPlan = new TrainPlan();
//                BeanUtils.copyProperties(trainPlanAddOrEditPo, trainPlan);
//                trainPlan.setTargetItem(a.getTargetItem());
//                trainPlan.setExecutor(a.getExecutor());
//                String s = UUID.randomUUID().toString().replaceAll("-", "");
//                trainPlan.setPlanCode(s);
//                trainPlan.setStatus(1);//待填写
//                trainPlan.setCreatePersonCode(user.getUserCode());
//                trainPlan.setCreatePersonName(user.getUserName());
//                trainPlan.setCreateTime(LocalDateTime.now());
//                trainPlan.setUpdatePersonCode(user.getUserCode());
//                trainPlan.setUpdatePersonName(user.getUserName());
//                trainPlan.setUpdateTime(LocalDateTime.now());
//                trainPlans.add(trainPlan);
//            });
//        }
//
//        if (!trainPlanItems.isEmpty()) {
//            trainPlanItemService.saveBatch(trainPlanItems);
//        }
        TrainPlan trainPlan = new TrainPlan();
        BeanUtils.copyProperties(trainPlanAddOrEditPo, trainPlan);
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        trainPlan.setPlanCode(s);
        trainPlan.setStatus(2);//待填写
        trainPlan.setCreatePersonCode(user.getUserCode());
        trainPlan.setCreatePersonName(user.getUserName());
        trainPlan.setCreateTime(LocalDateTime.now());
        trainPlan.setUpdatePersonCode(user.getUserCode());
        trainPlan.setUpdatePersonName(user.getUserName());
        trainPlan.setUpdateTime(LocalDateTime.now());
//        this.saveBatch(trainPlans);
        return  this.save(trainPlan);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(TrainPlanAddOrEditPo trainPlanAddOrEditPo) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        IBeanUtil.paramVerify(trainPlanAddOrEditPo, "planCode");
        TrainPlan trainPlan = new TrainPlan();
        BeanUtils.copyProperties(trainPlanAddOrEditPo, trainPlan);
        trainPlan.setUpdatePersonCode(user.getUserCode());
        trainPlan.setUpdatePersonName(user.getUserName());
        trainPlan.setUpdateTime(LocalDateTime.now());
        trainPlan.setExecutor(null);
        LambdaQueryWrapper<TrainPlan> eq = Wrappers.lambdaQuery(TrainPlan.class).eq(TrainPlan::getPlanCode, trainPlanAddOrEditPo.getPlanCode());
        this.update(trainPlan, eq);
        //保存各种计划
        List<TrainPlanActivity> trainPlanActivityList = trainPlanAddOrEditPo.getTrainPlanActivityList();
        List<TrainPlanTeach> trainPlanTeachList = trainPlanAddOrEditPo.getTrainPlanTeachList();
        List<TrainPlanEducation> trainPlanEducationList = trainPlanAddOrEditPo.getTrainPlanEducationList();
        List<TrainPlanStage> trainPlanStageList = trainPlanAddOrEditPo.getTrainPlanStageList();
        List<TrainPlanItem> trainPlanItemList = trainPlanAddOrEditPo.getTrainPlanItemList();
        trainPlanActivityService.remove(new QueryWrapper<TrainPlanActivity>().eq("PLAN_CODE", trainPlanAddOrEditPo.getPlanCode()));
        trainPlanTeachService.remove(new QueryWrapper<TrainPlanTeach>().eq("PLAN_CODE", trainPlanAddOrEditPo.getPlanCode()));
        trainPlanEducationService.remove(new QueryWrapper<TrainPlanEducation>().eq("PLAN_CODE", trainPlanAddOrEditPo.getPlanCode()));
        trainPlanStageService.remove(new QueryWrapper<TrainPlanStage>().eq("PLAN_CODE", trainPlanAddOrEditPo.getPlanCode()));
        trainPlanItemService.remove(new QueryWrapper<TrainPlanItem>().eq("PLAN_CODE", trainPlanAddOrEditPo.getPlanCode()));
        if (!trainPlanActivityList.isEmpty()) {
            trainPlanActivityList.stream().forEach(a -> {
                a.setPlanCode(trainPlanAddOrEditPo.getPlanCode());
                a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
            });
            trainPlanActivityService.saveBatch(trainPlanActivityList);
        }
        if (!trainPlanTeachList.isEmpty()) {
            trainPlanTeachList.stream().forEach(a -> {
                a.setPlanCode(trainPlanAddOrEditPo.getPlanCode());
                a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
            });
            trainPlanTeachService.saveBatch(trainPlanTeachList);
        }
        if (!trainPlanEducationList.isEmpty()) {
            trainPlanEducationList.stream().forEach(a -> {
                a.setPlanCode(trainPlanAddOrEditPo.getPlanCode());
                a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
            });
            trainPlanEducationService.saveBatch(trainPlanEducationList);
        }
        if (!trainPlanStageList.isEmpty()) {
            trainPlanStageList.stream().forEach(a -> {
                a.setPlanCode(trainPlanAddOrEditPo.getPlanCode());
                a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
            });
            trainPlanStageService.saveBatch(trainPlanStageList);
        }
        if (!trainPlanItemList.isEmpty()) {
            trainPlanItemList.stream().forEach(a -> {
                a.setPlanCode(trainPlanAddOrEditPo.getPlanCode());
                a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
            });
            trainPlanItemService.saveBatch(trainPlanItemList);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(TrainPlan trainPlan) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        LambdaQueryWrapper<TrainPlan> eq = Wrappers.lambdaQuery(TrainPlan.class).eq(TrainPlan::getPlanCode, trainPlan.getPlanCode());
        TrainPlan one = this.getOne(eq);
        Integer num = trainExamMapper.selectCount(new QueryWrapper<TrainExam>().eq("PLAN_CODE", trainPlan.getPlanCode()));
        if (one == null) {
            throw new BusinessException(ExceptionTrainEnum.DATA_NOT_EXIT);
        }
        if (!user.getUserCode().equals(one.getCreatePersonCode())) {
            throw new BusinessException(ExceptionTrainEnum.PLAN_DELETE_ERROR);
        }
        if (num > 0) {
            throw new BusinessException(ExceptionTrainEnum.PLAN_USED_ERROR);
        }
        return this.remove(eq);
    }

    @Override
    public Page<TrainPlanVo> pageQuery(TrainPlanPageQueryPo trainPlanPageQueryPo) {
        Page page = new Page(trainPlanPageQueryPo.getCurrent(), trainPlanPageQueryPo.getSize());
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        trainPlanPageQueryPo.setLoginCode(user.getUserCode());
        if (StrUtil.isNotBlank(trainPlanPageQueryPo.getTimeStart()) && StrUtil.isNotBlank(trainPlanPageQueryPo.getTimeEnd())){
            trainPlanPageQueryPo.setTimeStart(trainPlanPageQueryPo.getTimeStart()+" 00:00:00");
            trainPlanPageQueryPo.setTimeEnd(trainPlanPageQueryPo.getTimeEnd()+" 23:59:59");
        }
        Page<TrainPlanVo> trainPlanVoPage = this.baseMapper.pageQuery(page, trainPlanPageQueryPo);
//        List<UserVo> personMap = this.baseMapper.getPersonMap();
//        Map<String, String> map = personMap.stream().collect(Collectors.toMap(UserVo::getUserCode, UserVo::getUserName, (k1, k2) -> k1));
//        List<TrainPlanVo> records = trainPlanVoPage.getRecords();
//        List<DeptVo> dept = this.baseMapper.getDept();
//        Map<String, String> deptMap = dept.stream().collect(Collectors.toMap(DeptVo::getDeptCode, DeptVo::getDeptName, (k1, k2) -> k1));
//        //处理执行人和处理目标对象
//        if (!records.isEmpty()) {
//            records.stream().forEach(a -> {
//                String name = "";
//                String code = "";
//                JSONArray jsonArray = JSONObject.parseArray(a.getExecutor());
//                if (!jsonArray.isEmpty()) {
//                    for (int i = 0; i < jsonArray.size(); i++) {
//                        String s = map.get(jsonArray.get(i));
//                        if (s != null && !s.equals("null")) {
//                            name += s;
//                            code += jsonArray.get(i);
//                            if (i < jsonArray.size() - 1) {
//                                name += ",";
//                                code += ",";
//                            }
//                        }
//                    }
//                }
//                a.setExecutor(name);
//                a.setExecutorCode(code);
//                //  处理目标对象
//                String deptName = "";
//                String deptCode = "";
//                JSONArray deptArray = JSONObject.parseArray(a.getTargetItem());
//                if (!deptArray.isEmpty()) {
//                    for (int i = 0; i < deptArray.size(); i++) {
//                        String s = deptMap.get(deptArray.get(i));
//                        if (s != null && !s.equals("null")) {
//                            deptName += s;
//                            deptCode += deptArray.get(i);
//                            if (i < deptArray.size() - 1) {
//                                deptName += ",";
//                                deptCode += ",";
//                            }
//                        }
//                    }
//                }
//                a.setTargetItemName(deptName);
//                a.setTargetItem(deptCode);
//            });
//        }
//
//        trainPlanVoPage.setRecords(records);
        return trainPlanVoPage;
    }

    @Override
    public Page<TrainPlanVo> doorPageQuery(TrainPlanPageQueryPo trainPlanPageQueryPo) {
        Page page = new Page(trainPlanPageQueryPo.getCurrent(), trainPlanPageQueryPo.getSize());
        if (StrUtil.isNotBlank(trainPlanPageQueryPo.getTimeStart()) && StrUtil.isNotBlank(trainPlanPageQueryPo.getTimeEnd())){
            trainPlanPageQueryPo.setTimeStart(trainPlanPageQueryPo.getTimeStart()+" 00:00:00");
            trainPlanPageQueryPo.setTimeEnd(trainPlanPageQueryPo.getTimeEnd()+" 23:59:59");
        }
        Page<TrainPlanVo> trainPlanVoPage = this.baseMapper.doorPageQuery(page, trainPlanPageQueryPo);
//        List<UserVo> personMap = this.baseMapper.getPersonMap();
//        Map<String, String> map = personMap.stream().collect(Collectors.toMap(UserVo::getUserCode, UserVo::getUserName, (k1, k2) -> k1));
//        List<TrainPlanVo> records = trainPlanVoPage.getRecords();
//        List<DeptVo> dept = this.baseMapper.getDept();
//        Map<String, String> deptMap = dept.stream().collect(Collectors.toMap(DeptVo::getDeptCode, DeptVo::getDeptName, (k1, k2) -> k1));
//        //处理执行人和处理目标对象
//        if (!records.isEmpty()) {
//            records.stream().forEach(a -> {
//                String name = "";
//                String code = "";
//                JSONArray jsonArray = JSONObject.parseArray(a.getExecutor());
//                if (!jsonArray.isEmpty()) {
//                    for (int i = 0; i < jsonArray.size(); i++) {
//                        String s = map.get(jsonArray.get(i));
//                        if (s != null && !s.equals("null")) {
//                            name += s;
//                            code += jsonArray.get(i);
//                            if (i < jsonArray.size() - 1) {
//                                name += ",";
//                                code += ",";
//                            }
//                        }
//                    }
//                }
//                a.setExecutor(name);
//                a.setExecutorCode(code);
//                //  处理目标对象
//                String deptName = "";
//                String deptCode = "";
//                JSONArray deptArray = JSONObject.parseArray(a.getTargetItem());
//                if (!deptArray.isEmpty()) {
//                    for (int i = 0; i < deptArray.size(); i++) {
//                        String s = deptMap.get(deptArray.get(i));
//                        if (s != null && !s.equals("null")) {
//                            deptName += s;
//                            deptCode += deptArray.get(i);
//                            if (i < deptArray.size() - 1) {
//                                deptName += ",";
//                                deptCode += ",";
//                            }
//                        }
//                    }
//                }
//                a.setTargetItemName(deptName);
//                a.setTargetItem(deptCode);
//            });
//        }
//        trainPlanVoPage.setRecords(records);
        return trainPlanVoPage;
    }

    @Override
    public TrainPlanDetailVo detail(TrainPlan trainPlan) {
        IBeanUtil.paramVerify(trainPlan, "planCode");
        LambdaQueryWrapper<TrainPlan> eq = Wrappers.lambdaQuery(TrainPlan.class).eq(TrainPlan::getPlanCode, trainPlan.getPlanCode());
        TrainPlan one = this.getOne(eq);
//        List<UserVo> personMap = this.baseMapper.getPersonMap();
//        Map<String, String> map = personMap.stream().collect(Collectors.toMap(UserVo::getUserCode, UserVo::getUserName, (k1, k2) -> k1));
//        List<DeptVo> dept = this.baseMapper.getDept();
//        Map<String, String> deptMap = dept.stream().collect(Collectors.toMap(DeptVo::getDeptCode, DeptVo::getDeptName, (k1, k2) -> k1));
        TrainPlanDetailVo trainPlanDetailVo = new TrainPlanDetailVo();
//        if (one != null) {
            BeanUtils.copyProperties(one, trainPlanDetailVo);
//            //  处理目标对象
//            String deptName = "";
//            String deptCode = "";
//            JSONArray deptArray = JSONObject.parseArray(one.getTargetItem());
//            if (!deptArray.isEmpty()) {
//                for (int i = 0; i < deptArray.size(); i++) {
//                    String s = deptMap.get(deptArray.get(i));
//                    deptName += s;
//                    deptCode += deptArray.get(i);
//                    if (i < deptArray.size() - 1) {
//                        deptName += ",";
//                        deptCode += ",";
//                    }
//                }
//            }
//            //处理执行人
//            String name = "";
//            String code = "";
//            JSONArray jsonArray = JSONObject.parseArray(one.getExecutor());
//            if (!jsonArray.isEmpty()) {
//                for (int i = 0; i < jsonArray.size(); i++) {
//                    String s = map.get(jsonArray.get(i));
//                    name += s;
//                    code += jsonArray.get(i);
//                    if (i < jsonArray.size() - 1) {
//                        name += ",";
//                        code += ",";
//                    }
//                }
//            }
//            trainPlanDetailVo.setExecutor(name);
//            trainPlanDetailVo.setExecutorCode(code);
//            trainPlanDetailVo.setTargetItemName(deptName);
//            trainPlanDetailVo.setTargetItem(deptCode);
//            trainPlanDetailVo.setTrainPlanActivityList(trainPlanActivityService.list(new QueryWrapper<TrainPlanActivity>().eq("PLAN_CODE", trainPlan.getPlanCode())));
//            trainPlanDetailVo.setTrainPlanTeachList(trainPlanTeachService.list(new QueryWrapper<TrainPlanTeach>().eq("PLAN_CODE", trainPlan.getPlanCode())));
//            trainPlanDetailVo.setTrainPlanEducationList(trainPlanEducationService.list(new QueryWrapper<TrainPlanEducation>().eq("PLAN_CODE", trainPlan.getPlanCode())));
//            trainPlanDetailVo.setTrainPlanStageList(trainPlanStageService.list(new QueryWrapper<TrainPlanStage>().eq("PLAN_CODE", trainPlan.getPlanCode())));
//            trainPlanDetailVo.setTrainPlanItemList(trainPlanItemService.list(new QueryWrapper<TrainPlanItem>().eq("PLAN_CODE", trainPlan.getPlanCode())));
//        }
        return trainPlanDetailVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean FillIn(TrainPlanFillInPo trainPlanFillInPo) {
        IBeanUtil.paramVerify(trainPlanFillInPo, "planCode");
        TrainPlan trainPlan = new TrainPlan();
        BeanUtils.copyProperties(trainPlanFillInPo, trainPlan);
        trainPlan.setStatus(2);
        LambdaQueryWrapper<TrainPlan> eq = Wrappers.lambdaQuery(TrainPlan.class).eq(TrainPlan::getPlanCode, trainPlanFillInPo.getPlanCode());
        this.update(trainPlan, eq);//编辑计划信息
        //保存各种计划
        List<TrainPlanActivity> trainPlanActivityList = trainPlanFillInPo.getTrainPlanActivityList();
        List<TrainPlanTeach> trainPlanTeachList = trainPlanFillInPo.getTrainPlanTeachList();
        List<TrainPlanEducation> trainPlanEducationList = trainPlanFillInPo.getTrainPlanEducationList();
        List<TrainPlanStage> trainPlanStageList = trainPlanFillInPo.getTrainPlanStageList();
        List<TrainPlanItem> trainPlanItemList = trainPlanFillInPo.getTrainPlanItemList();
        if (!trainPlanActivityList.isEmpty()) {
            trainPlanActivityList.stream().forEach(a -> {
                a.setPlanCode(trainPlanFillInPo.getPlanCode());
                a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
            });
            trainPlanActivityService.saveBatch(trainPlanActivityList);
        }
        if (!trainPlanTeachList.isEmpty()) {
            trainPlanTeachList.stream().forEach(a -> {
                a.setPlanCode(trainPlanFillInPo.getPlanCode());
                a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
            });
            trainPlanTeachService.saveBatch(trainPlanTeachList);
        }
        if (!trainPlanEducationList.isEmpty()) {
            trainPlanEducationList.stream().forEach(a -> {
                a.setPlanCode(trainPlanFillInPo.getPlanCode());
                a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
            });
            trainPlanEducationService.saveBatch(trainPlanEducationList);
        }
        if (!trainPlanStageList.isEmpty()) {
            trainPlanStageList.stream().forEach(a -> {
                a.setPlanCode(trainPlanFillInPo.getPlanCode());
                a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
            });
            trainPlanStageService.saveBatch(trainPlanStageList);
        }
        if (!trainPlanItemList.isEmpty()) {
            trainPlanItemList.stream().forEach(a -> {
                a.setPlanCode(trainPlanFillInPo.getPlanCode());
                a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
            });
            trainPlanItemService.saveBatch(trainPlanItemList);
        }
        return true;
    }

    @Override
    public List<TrainPlanActivity> activityParse(MultipartFile file) {
        List<TrainPlanActivity> returnList = new LinkedList<>();
        if (file.isEmpty()) {
            throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
        }
        List<TrainPlanActivityExcelMappingEntity> fl = new ArrayList<>();
        try {
            fl = ExcelUtils.importExcel(file, TrainPlanActivityExcelMappingEntity.class);
            if (CollUtil.isEmpty(fl)) {
                throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
            }
            fl = fl.stream().filter(purchaseListEntity -> !ObjectSelfUtil.isAllFieldNull(purchaseListEntity)).collect(Collectors.toList());
            if (CollUtil.isEmpty(fl)) {
                throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
            }
            if (!fl.isEmpty()) {
                fl.stream().forEach(a -> {
                    TrainPlanActivity trainPlanActivity = new TrainPlanActivity();
                    BeanUtils.copyProperties(a, trainPlanActivity);
                    returnList.add(trainPlanActivity);
                });
            }
        } catch (IOException e) {
            throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
        }
        return returnList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean activityBatchAdd(List<TrainPlanActivity> trainPlanActivityList) {
        trainPlanActivityList.stream().forEach(a -> {
            a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
        });
        return trainPlanActivityService.saveBatch(trainPlanActivityList);
    }

    @Override
    public List<TrainPlanTeach> teachParse(MultipartFile file) {
        List<TrainPlanTeach> returnList = new LinkedList<>();
        if (file.isEmpty()) {
            throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
        }
        List<TrainPlanTeachExcelMappingEntity> fl = new ArrayList<>();
        try {
            fl = ExcelUtils.importExcel(file, TrainPlanTeachExcelMappingEntity.class);
            if (CollUtil.isEmpty(fl)) {
                throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
            }
            fl = fl.stream().filter(purchaseListEntity -> !ObjectSelfUtil.isAllFieldNull(purchaseListEntity)).collect(Collectors.toList());
            if (CollUtil.isEmpty(fl)) {
                throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
            }
            if (!fl.isEmpty()) {
                fl.stream().forEach(a -> {
                    TrainPlanTeach trainPlanTeach = new TrainPlanTeach();
                    BeanUtils.copyProperties(a, trainPlanTeach);
                    returnList.add(trainPlanTeach);
                });
            }
        } catch (IOException e) {
            throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
        }
        return returnList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean teachBatchAdd(List<TrainPlanTeach> trainPlanTeachList) {
        trainPlanTeachList.stream().forEach(a -> {
            a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
        });
        return trainPlanTeachService.saveBatch(trainPlanTeachList);
    }

    @Override
    public List<TrainPlanEducation> educationParse(MultipartFile file) {
        List<TrainPlanEducation> returnList = new LinkedList<>();
        if (file.isEmpty()) {
            throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
        }
        List<TrainPlanEducationExcelMappingEntity> fl = new ArrayList<>();
        try {
            fl = ExcelUtils.importExcel(file, TrainPlanEducationExcelMappingEntity.class);
            if (CollUtil.isEmpty(fl)) {
                throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
            }
            fl = fl.stream().filter(purchaseListEntity -> !ObjectSelfUtil.isAllFieldNull(purchaseListEntity)).collect(Collectors.toList());
            if (CollUtil.isEmpty(fl)) {
                throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
            }
            if (!fl.isEmpty()) {
                fl.stream().forEach(a -> {
                    TrainPlanEducation trainPlanEducation = new TrainPlanEducation();
                    BeanUtils.copyProperties(a, trainPlanEducation);
                    returnList.add(trainPlanEducation);
                });
            }
        } catch (IOException e) {
            throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
        }
        return returnList;
    }

    @Override
    public boolean educationBatchAdd(List<TrainPlanEducation> trainPlanEducationList) {
        trainPlanEducationList.stream().forEach(a -> {
            a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
        });
        return trainPlanEducationService.saveBatch(trainPlanEducationList);
    }

    @Override
    public List<TrainPlanStage> stageParse(MultipartFile file) {
        List<TrainPlanStage> returnList = new LinkedList<>();
        if (file.isEmpty()) {
            throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
        }
        List<TrainPlanStageExcelMappingEntity> fl = new ArrayList<>();
        try {
            fl = ExcelUtils.importExcel(file, TrainPlanStageExcelMappingEntity.class);
            if (CollUtil.isEmpty(fl)) {
                throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
            }
            fl = fl.stream().filter(purchaseListEntity -> !ObjectSelfUtil.isAllFieldNull(purchaseListEntity)).collect(Collectors.toList());
            if (CollUtil.isEmpty(fl)) {
                throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
            }
            if (!fl.isEmpty()) {
                fl.stream().forEach(a -> {
                    TrainPlanStage trainPlanStage = new TrainPlanStage();
                    BeanUtils.copyProperties(a, trainPlanStage);
                    returnList.add(trainPlanStage);
                });
            }
        } catch (IOException e) {
            throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
        }
        return returnList;
    }

    @Override
    public boolean stageBatchAdd(List<TrainPlanStage> trainPlanStageList) {
        trainPlanStageList.stream().forEach(a -> {
            a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
        });
        return trainPlanStageService.saveBatch(trainPlanStageList);
    }

    @Override
    public List<TrainPlanItem> itemParse(MultipartFile file) {
        List<TrainPlanItem> returnList = new LinkedList<>();
        if (file.isEmpty()) {
            throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
        }
        List<TrainPlanItemExcelMappingEntity> fl = new ArrayList<>();
        try {
            fl = ExcelUtils.importExcel(file, TrainPlanItemExcelMappingEntity.class);
            if (CollUtil.isEmpty(fl)) {
                throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
            }
            fl = fl.stream().filter(purchaseListEntity -> !ObjectSelfUtil.isAllFieldNull(purchaseListEntity)).collect(Collectors.toList());
            if (CollUtil.isEmpty(fl)) {
                throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
            }
            if (!fl.isEmpty()) {
                fl.stream().forEach(a -> {
                    TrainPlanItem trainPlanItem = new TrainPlanItem();
                    BeanUtils.copyProperties(a, trainPlanItem);
                    returnList.add(trainPlanItem);
                });
            }
        } catch (IOException e) {
            throw new BusinessException(ExceptionTrainEnum.PARSE_ERROR);
        }
        return returnList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean itemBatchAdd(List<TrainPlanItem> trainPlanItemList) {
        trainPlanItemList.stream().forEach(a -> {
            a.setItemCode(UUID.randomUUID().toString().replaceAll("-", ""));
        });
        return trainPlanItemService.saveBatch(trainPlanItemList);
    }

    @Override
    public boolean stageDownload(TrainPlanFillInDownloadPo trainPlanFillInDownloadPo, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        Integer type = trainPlanFillInDownloadPo.getType();
        String path = "";
        if (type == 0) {
            path = "\\templates\\trainPlanActivityTemplateOne.xls";
        }
        if (type == 1) {
            path = "\\templates\\trainPlanTeachExcelTemplateOne.xls";
        }
        if (type == 2) {
            path = "\\templates\\trainPlanEducationTemplate.xls";
        }
        if (type == 3) {
            path = "\\templates\\trainPlanStageTemplateOne.xls";
        }
        if (type == 4) {
            path = "\\templates\\trainPlanItemTemplateOne.xls";
        }
        TemplateExportParams templatePath = new TemplateExportParams(ConvertTemplatePath.convertTemplatePath(path));
        try {
            if (type == 0) {
                ExcelUtils.exportExcel(templatePath, map, "活动安排导入模板", response);
            }
            if (type == 1) {
                ExcelUtils.exportExcel(templatePath, map, "教学安排导入模板", response);
            }
            if (type == 2) {
                ExcelUtils.exportExcel(templatePath, map, "职业教育工作计划导入模板", response);
            }
            if (type == 3) {
                ExcelUtils.exportExcel(templatePath, map, "阶段计划导入模板", response);
            }
            if (type == 4) {
                ExcelUtils.exportExcel(templatePath, map, "训练计划导入模板", response);
            }
        } catch (IOException e) {
            throw new BusinessException(ExceptionTrainEnum.TEMP_ERROR);
        }
        return true;
    }

    @Override
    public TrainArchiveVo queryPlan() {
        TrainArchiveVo trainArchiveVo = new TrainArchiveVo();
        trainArchiveVo.setYearPlan(this.baseMapper.queryPlan(1));
        trainArchiveVo.setQuarterPlan(this.baseMapper.queryPlan(2));
        trainArchiveVo.setMonthPlan(this.baseMapper.queryPlan(3));
        trainArchiveVo.setWeekPlan(this.baseMapper.queryPlan(4));
        trainArchiveVo.setSpecialPlan(this.baseMapper.queryPlan(5));
        trainArchiveVo.setTrainingPlan(this.baseMapper.queryPlan(6));
        return trainArchiveVo;
    }

    @Override
    public AssessmentVo assessment(TrainAndCasePo trainAndCasePo) {
        AssessmentVo assessmentVo = new AssessmentVo();
        List<TrainExam> trainExams = trainExamMapper.trainExamByYear(trainAndCasePo.getYear());
        if (trainExams != null) {
            assessmentVo.setNum(trainExams.size());
            assessmentVo.setTrainExamList(trainExams);
        }
        List<String> examCodes = trainExams.stream().map(TrainExam::getExamCode).collect(Collectors.toList());
        List<BigDecimal> iii = new ArrayList<>();
        List<BigDecimal> fff = new ArrayList<>();
        for (String examCode : examCodes) {
            // 总人数
            int sum = trainScoreService.count(Wrappers.<TrainScore>lambdaQuery().eq(TrainScore::getExamCode, examCode));
            // 及格人数
            int count = trainScoreService.count(Wrappers.<TrainScore>lambdaQuery()
                    .eq(TrainScore::getExamCode, examCode).gt(TrainScore::getScore, 60));
            BigDecimal aaa = new BigDecimal(sum);
            if (count != 0) {
                BigDecimal bbb = new BigDecimal(count);
                BigDecimal divide = bbb.divide(aaa, 2, BigDecimal.ROUND_HALF_UP);
                iii.add(divide);
            } else {
                iii.add(new BigDecimal(0));
            }
            int good = trainScoreService.count(Wrappers.<TrainScore>lambdaQuery()
                    .eq(TrainScore::getExamCode, examCode).gt(TrainScore::getScore, 90));
            if (good != 0) {
                BigDecimal ccc = new BigDecimal(good);
                BigDecimal divide = ccc.divide(aaa, 2, BigDecimal.ROUND_HALF_UP);
                fff.add(divide);

            } else {
                fff.add(new BigDecimal(0));
            }
        }
        BigDecimal sum = iii.stream()
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        if (sum.compareTo(BigDecimal.ZERO) != 0) {
            BigDecimal divide = sum.divide(new BigDecimal(iii.size()), 2, BigDecimal.ROUND_HALF_UP);
            BigDecimal multiply = divide.multiply(new BigDecimal(100));
            assessmentVo.setAveragePassRate(multiply.toString());
        } else {
            assessmentVo.setAveragePassRate("0.00");
        }
        BigDecimal add = fff.stream()
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        if (add.compareTo(BigDecimal.ZERO) != 0) {
            BigDecimal ggg = add.divide(new BigDecimal(iii.size()), 2, BigDecimal.ROUND_HALF_UP);
            BigDecimal decimal = ggg.multiply(new BigDecimal(100));
            assessmentVo.setAverageExcellentRate(decimal.toString());
        } else {
            assessmentVo.setAverageExcellentRate("0.00");
        }

        return assessmentVo;
    }

    @Override
    public HashMap<String, Object> statisticsByExamCode(TrainAndCasePo trainAndCasePo) {
        List<String> notList = new LinkedList<>();
//        for (Integer i = 0; i < 60; i++) {
//            notList.add(i.toString() + ".");
//        }
        List<String> qualifiedList = new LinkedList<>();
//        for (Integer i = 60; i < 70; i++) {
//            qualifiedList.add(i.toString() + ".");
//        }
        List<String> goodList = new LinkedList<>();
//        for (Integer i = 70; i < 90; i++) {
//            goodList.add(i.toString() + ".");
//        }
        List<String> outstandingList = new LinkedList<>();
//        for (Integer i = 90; i <= 100; i++) {
//            outstandingList.add(i.toString() + ".");
//        }

        List<String> rate1 = new LinkedList<>();
        rate1.add("不合格");
        List<String> rate2 = new LinkedList<>();
        rate2.add("合格");
        List<String> rate3 = new LinkedList<>();
        rate3.add("良好");
        List<String> rate4 = new LinkedList<>();
        rate4.add("优秀");

        HashMap<String, Object> hashMap = new HashMap<>();
        int num1 = trainScoreService.count(new QueryWrapper<TrainScore>().eq("EXAM_CODE", trainAndCasePo.getExamCode()).isNotNull("SCORE"));//所有
        int num2 = trainScoreService.queryScore1(notList, trainAndCasePo.getExamCode(), rate1);//不合格
        Integer type=null;;
        type=1;
        int num3 = trainScoreService.queryScore(qualifiedList, trainAndCasePo.getExamCode(), rate2,type);//合格
        type=2;
        int num4 = trainScoreService.queryScore(goodList, trainAndCasePo.getExamCode(), rate3,type);//良好
        type=3;
        int num5 = trainScoreService.queryScore(outstandingList, trainAndCasePo.getExamCode(), rate4,type);//优秀
        hashMap.put("num1", num1);
        hashMap.put("num2", num2);
        hashMap.put("num3", num3);
        hashMap.put("num4", num4);
        hashMap.put("num5", num5);
        if (num1 > 0) {
            NumberFormat numberFormat = NumberFormat.getPercentInstance();
            numberFormat.setMinimumFractionDigits(2);
            hashMap.put("1", numberFormat.format(num2 / (num1 * 1.00)));
            hashMap.put("2", numberFormat.format(num3 / (num1 * 1.00)));
            hashMap.put("3", numberFormat.format(num4 / (num1 * 1.00)));
            hashMap.put("4", numberFormat.format(num5 / (num1 * 1.00)));
        } else {
            hashMap.put("1", "0.0%");
            hashMap.put("2", "0.0%");
            hashMap.put("3", "0.0%");
            hashMap.put("4", "0.0%");
        }
        return hashMap;
    }

    @Override
    public List<HashMap<String, Object>> planStatistics(TrainAndCasePo trainAndCasePo) {
        return this.baseMapper.planStatistics(trainAndCasePo.getYear());
    }

    @Override
    public List<HashMap<String, Object>> byCarStatistics(TrainAndCasePo trainAndCasePo) {
        return this.baseMapper.byCarStatistics(trainAndCasePo.getYear());
    }

    @Override
    public CaseStatisticsVo caseStatistics(TrainAndCasePo trainAndCasePo) {
        IBeanUtil.paramVerify(trainAndCasePo, "year");
        CaseStatisticsVo caseStatisticsVo = new CaseStatisticsVo();
        List<DealProcessNodeEntity> dealProcessNodeEntities = dealProcessNodeService.list(Wrappers.<DealProcessNodeEntity>lambdaQuery()
                .like(DealProcessNodeEntity::getCreateTime, trainAndCasePo.getYear())
                .isNotNull(DealProcessNodeEntity::getRecordCode));
        int count = 0;
        if (CollUtil.isNotEmpty(dealProcessNodeEntities)) {
            Map<String, List<DealProcessNodeEntity>> map = dealProcessNodeEntities.stream().collect(Collectors.groupingBy(DealProcessNodeEntity::getRecordCode));
            count = map.size();
        }
        HashMap<String, Object> deal = new HashMap<>();
        int aaa = 0;

        if (count != 0) {
            List<DealDataEntity> dealDataEntities = dealDataService.list(Wrappers.<DealDataEntity>lambdaQuery()
                    .like(DealDataEntity::getCreateTime, trainAndCasePo.getYear()));
            if (CollUtil.isNotEmpty(dealDataEntities)) {
                Set<String> recordCodes = dealDataEntities.stream().map(DealDataEntity::getRecordCode).collect(Collectors.toSet());
                Map<String, List<DealDataEntity>> map = dealDataEntities.stream().collect(Collectors.groupingBy(DealDataEntity::getRecordCode));
                for (String recordCode : recordCodes) {
                    List<DealDataEntity> dataEntities = map.get(recordCode);
                    Set<Integer> collect = dataEntities.stream().map(DealDataEntity::getState).collect(Collectors.toSet());
                    if (collect.size() == 1 && collect.contains(4)) {
                        aaa = aaa + 1;
                    }
                }
                deal.put("all", count);
                deal.put("ed", aaa);
            }
        } else {
            deal.put("all", 0);
            deal.put("ed", aaa);
        }
        caseStatisticsVo.setDeal(deal);
        /*** 心理咨询留言*/
        HashMap<String, Object> psychological = new HashMap<>();
        psychological.put("all", messageNoteMapper.noteNum(1, 1, trainAndCasePo.getYear()));
        psychological.put("ed", messageNoteMapper.noteNum(2, 1, trainAndCasePo.getYear()));
        caseStatisticsVo.setPsychological(psychological);
        /*** 法律援助留言*/
        HashMap<String, Object> legalAid = new HashMap<>();
        legalAid.put("all", messageNoteMapper.noteNum(1, 2, trainAndCasePo.getYear()));
        legalAid.put("ed", messageNoteMapper.noteNum(2, 2, trainAndCasePo.getYear()));
        caseStatisticsVo.setLegalAid(legalAid);
        /*** 信箱来件留言*/
        HashMap<String, Object> mailbox = new HashMap<>();
        mailbox.put("all", leadingCadreService.count(Wrappers.<LeadingCadreEntity>lambdaQuery()
                .like(LeadingCadreEntity::getCreateTime, trainAndCasePo.getYear())));
        List<LeadingCadreEntity> leadingCadreEntities = leadingCadreService.list(Wrappers.<LeadingCadreEntity>lambdaQuery()
                .like(LeadingCadreEntity::getCreateTime, trainAndCasePo.getYear()));
        if (CollUtil.isNotEmpty(leadingCadreEntities)) {
            Set<String> writeCodes = leadingCadreEntities.stream().map(LeadingCadreEntity::getWriteCode).collect(Collectors.toSet());
            List<MessageReceive> messageReceives = messageReceiveService.list(Wrappers.<MessageReceive>lambdaQuery()
                    .in(MessageReceive::getMessageCode, writeCodes)
                    .like(MessageReceive::getCreateTime, trainAndCasePo.getYear()));
            if (CollUtil.isNotEmpty(messageReceives)) {
                Map<String, List<MessageReceive>> map = messageReceives.stream().collect(Collectors.groupingBy(MessageReceive::getMessageCode));
                mailbox.put("ed", map.size());
            } else {
                mailbox.put("ed", 0);
            }
        } else {
            mailbox.put("ed", 0);

        }

        caseStatisticsVo.setMailbox(mailbox);
        /*** 网上办事申请*/
        HashMap<String, Object> online = new HashMap<>();
        online.put("all", repairsMessageMapper.repairsNum(1, trainAndCasePo.getYear()));
        online.put("ed", repairsMessageMapper.repairsNum(2, trainAndCasePo.getYear()));
        caseStatisticsVo.setOnline(online);
        return caseStatisticsVo;
    }

    @Override
    public List<HashMap<String, Object>> statisticsByMonth(TrainAndCasePo trainAndCasePo) {
        List<HashMap<String, Object>> byMonths = new LinkedList<>();
        if (trainAndCasePo.getType() == 2 || trainAndCasePo.getType() == 3) {//心理咨询留言 ||法律援助留言
            Integer sign = 1;
            if (trainAndCasePo.getType() == 2) {
                sign = 1;
            }
            if (trainAndCasePo.getType() == 3) {
                sign = 2;
            }
            HashMap<String, Object> byMonth1 = new HashMap<>();
            byMonth1.put("month", "1");
            byMonth1.put("all", repairsMessageMapper.caseNum(1, trainAndCasePo.getYear() + "-01", sign));
            byMonth1.put("ed", repairsMessageMapper.caseNum(2, trainAndCasePo.getYear() + "-01", sign));
            byMonths.add(byMonth1);

            HashMap<String, Object> byMonth2 = new HashMap<>();
            byMonth2.put("month", "2");
            byMonth2.put("all", repairsMessageMapper.caseNum(1, trainAndCasePo.getYear() + "-02", sign));
            byMonth2.put("ed", repairsMessageMapper.caseNum(2, trainAndCasePo.getYear() + "-02", sign));
            byMonths.add(byMonth2);

            HashMap<String, Object> byMonth3 = new HashMap<>();
            byMonth3.put("month", "3");
            byMonth3.put("all", repairsMessageMapper.caseNum(1, trainAndCasePo.getYear() + "-03", sign));
            byMonth3.put("ed", repairsMessageMapper.caseNum(2, trainAndCasePo.getYear() + "-03", sign));
            byMonths.add(byMonth3);

            HashMap<String, Object> byMonth4 = new HashMap<>();
            byMonth4.put("month", "4");
            byMonth4.put("all", repairsMessageMapper.caseNum(1, trainAndCasePo.getYear() + "-04", sign));
            byMonth4.put("ed", repairsMessageMapper.caseNum(2, trainAndCasePo.getYear() + "-04", sign));
            byMonths.add(byMonth4);

            HashMap<String, Object> byMonth5 = new HashMap<>();
            byMonth5.put("month", "5");
            byMonth5.put("all", repairsMessageMapper.caseNum(1, trainAndCasePo.getYear() + "-05", sign));
            byMonth5.put("ed", repairsMessageMapper.caseNum(2, trainAndCasePo.getYear() + "-05", sign));
            byMonths.add(byMonth5);

            HashMap<String, Object> byMonth6 = new HashMap<>();
            byMonth6.put("month", "6");
            byMonth6.put("all", repairsMessageMapper.caseNum(1, trainAndCasePo.getYear() + "-06", sign));
            byMonth6.put("ed", repairsMessageMapper.caseNum(2, trainAndCasePo.getYear() + "-06", sign));
            byMonths.add(byMonth6);

            HashMap<String, Object> byMonth7 = new HashMap<>();
            byMonth7.put("month", "7");
            byMonth7.put("all", repairsMessageMapper.caseNum(1, trainAndCasePo.getYear() + "-07", sign));
            byMonth7.put("ed", repairsMessageMapper.caseNum(2, trainAndCasePo.getYear() + "-07", sign));
            byMonths.add(byMonth7);

            HashMap<String, Object> byMonth8 = new HashMap<>();
            byMonth8.put("month", "8");
            byMonth8.put("all", repairsMessageMapper.caseNum(1, trainAndCasePo.getYear() + "-08", sign));
            byMonth8.put("ed", repairsMessageMapper.caseNum(2, trainAndCasePo.getYear() + "-08", sign));
            byMonths.add(byMonth8);

            HashMap<String, Object> byMonth9 = new HashMap<>();
            byMonth9.put("month", "9");
            byMonth9.put("all", repairsMessageMapper.caseNum(1, trainAndCasePo.getYear() + "-09", sign));
            byMonth9.put("ed", repairsMessageMapper.caseNum(2, trainAndCasePo.getYear() + "-09", sign));
            byMonths.add(byMonth9);

            HashMap<String, Object> byMonth10 = new HashMap<>();
            byMonth10.put("month", "10");
            byMonth10.put("all", repairsMessageMapper.caseNum(1, trainAndCasePo.getYear() + "-10", sign));
            byMonth10.put("ed", repairsMessageMapper.caseNum(2, trainAndCasePo.getYear() + "-10", sign));
            byMonths.add(byMonth10);

            HashMap<String, Object> byMonth11 = new HashMap<>();
            byMonth11.put("month", "11");
            byMonth11.put("all", repairsMessageMapper.caseNum(1, trainAndCasePo.getYear() + "-11", sign));
            byMonth11.put("ed", repairsMessageMapper.caseNum(2, trainAndCasePo.getYear() + "-11", sign));
            byMonths.add(byMonth11);

            HashMap<String, Object> byMonth12 = new HashMap<>();
            byMonth12.put("month", "12");
            byMonth12.put("all", repairsMessageMapper.caseNum(1, trainAndCasePo.getYear() + "-12", sign));
            byMonth12.put("ed", repairsMessageMapper.caseNum(2, trainAndCasePo.getYear() + "-12", sign));
            byMonths.add(byMonth12);
        }
        if (trainAndCasePo.getType() == 5) {
            HashMap<String, Object> byMonth1 = new HashMap<>();
            byMonth1.put("month", "1");
            byMonth1.put("all", repairsMessageMapper.caseNum1(1, trainAndCasePo.getYear() + "-01"));
            byMonth1.put("ed", repairsMessageMapper.caseNum1(2, trainAndCasePo.getYear() + "-01"));
            byMonths.add(byMonth1);

            HashMap<String, Object> byMonth2 = new HashMap<>();
            byMonth2.put("month", "2");
            byMonth2.put("all", repairsMessageMapper.caseNum1(1, trainAndCasePo.getYear() + "-02"));
            byMonth2.put("ed", repairsMessageMapper.caseNum1(2, trainAndCasePo.getYear() + "-02"));
            byMonths.add(byMonth2);

            HashMap<String, Object> byMonth3 = new HashMap<>();
            byMonth3.put("month", "3");
            byMonth3.put("all", repairsMessageMapper.caseNum1(1, trainAndCasePo.getYear() + "-03"));
            byMonth3.put("ed", repairsMessageMapper.caseNum1(2, trainAndCasePo.getYear() + "-03"));
            byMonths.add(byMonth3);

            HashMap<String, Object> byMonth4 = new HashMap<>();
            byMonth4.put("month", "4");
            byMonth4.put("all", repairsMessageMapper.caseNum1(1, trainAndCasePo.getYear() + "-04"));
            byMonth4.put("ed", repairsMessageMapper.caseNum1(2, trainAndCasePo.getYear() + "-04"));
            byMonths.add(byMonth4);

            HashMap<String, Object> byMonth5 = new HashMap<>();
            byMonth5.put("month", "5");
            byMonth5.put("all", repairsMessageMapper.caseNum1(1, trainAndCasePo.getYear() + "-05"));
            byMonth5.put("ed", repairsMessageMapper.caseNum1(2, trainAndCasePo.getYear() + "-05"));
            byMonths.add(byMonth5);

            HashMap<String, Object> byMonth6 = new HashMap<>();
            byMonth6.put("month", "6");
            byMonth6.put("all", repairsMessageMapper.caseNum1(1, trainAndCasePo.getYear() + "-06"));
            byMonth6.put("ed", repairsMessageMapper.caseNum1(2, trainAndCasePo.getYear() + "-06"));
            byMonths.add(byMonth6);

            HashMap<String, Object> byMonth7 = new HashMap<>();
            byMonth7.put("month", "7");
            byMonth7.put("all", repairsMessageMapper.caseNum1(1, trainAndCasePo.getYear() + "-07"));
            byMonth7.put("ed", repairsMessageMapper.caseNum1(2, trainAndCasePo.getYear() + "-07"));
            byMonths.add(byMonth7);

            HashMap<String, Object> byMonth8 = new HashMap<>();
            byMonth8.put("month", "8");
            byMonth8.put("all", repairsMessageMapper.caseNum1(1, trainAndCasePo.getYear() + "-08"));
            byMonth8.put("ed", repairsMessageMapper.caseNum1(2, trainAndCasePo.getYear() + "-08"));
            byMonths.add(byMonth8);

            HashMap<String, Object> byMonth9 = new HashMap<>();
            byMonth9.put("month", "9");
            byMonth9.put("all", repairsMessageMapper.caseNum1(1, trainAndCasePo.getYear() + "-09"));
            byMonth9.put("ed", repairsMessageMapper.caseNum1(2, trainAndCasePo.getYear() + "-09"));
            byMonths.add(byMonth9);

            HashMap<String, Object> byMonth10 = new HashMap<>();
            byMonth10.put("month", "10");
            byMonth10.put("all", repairsMessageMapper.caseNum1(1, trainAndCasePo.getYear() + "-10"));
            byMonth10.put("ed", repairsMessageMapper.caseNum1(2, trainAndCasePo.getYear() + "-10"));
            byMonths.add(byMonth10);

            HashMap<String, Object> byMonth11 = new HashMap<>();
            byMonth11.put("month", "11");
            byMonth11.put("all", repairsMessageMapper.caseNum1(1, trainAndCasePo.getYear() + "-11"));
            byMonth11.put("ed", repairsMessageMapper.caseNum1(2, trainAndCasePo.getYear() + "-11"));
            byMonths.add(byMonth11);

            HashMap<String, Object> byMonth12 = new HashMap<>();
            byMonth12.put("month", "12");
            byMonth12.put("all", repairsMessageMapper.caseNum1(1, trainAndCasePo.getYear() + "-12"));
            byMonth12.put("ed", repairsMessageMapper.caseNum1(2, trainAndCasePo.getYear() + "-12"));
            byMonths.add(byMonth12);
        }

        String trainAndCasePoYear = trainAndCasePo.getYear();
        int year = Integer.parseInt(trainAndCasePoYear);
        for (int i = 1; i < 13; i++) {
            HashMap<String, Object> months = new HashMap<>();
            HashMap<String, Object> writes = new HashMap<>();
            String date = null;
            if (i < 10) {
                date = year + "-0" + i;
            } else {
                date = year + "-" + i;
            }
            int count = 0;
            if (trainAndCasePo.getType() == 1) {
                List<DealProcessNodeEntity> dealProcessNodeEntities = dealProcessNodeService.list(Wrappers.<DealProcessNodeEntity>lambdaQuery()
                        .isNotNull(DealProcessNodeEntity::getRecordCode)
                        .like(DealProcessNodeEntity::getCreateTime, date)
                );
                if (CollUtil.isNotEmpty(dealProcessNodeEntities)) {
                    Map<String, List<DealProcessNodeEntity>> map = dealProcessNodeEntities.stream().collect(Collectors.groupingBy(DealProcessNodeEntity::getRecordCode));
                    count = map.size();
                }
                months.put("month", i);
                months.put("all", count);
                List<DealDataEntity> dealDataEntities = dealDataService.list(Wrappers.<DealDataEntity>lambdaQuery()
                        .like(DealDataEntity::getCreateTime, date)
                        .eq(DealDataEntity::getState, 4));
                if (CollUtil.isNotEmpty(dealDataEntities)) {
                    Map<String, List<DealDataEntity>> map = dealDataEntities.stream().collect(Collectors.groupingBy(DealDataEntity::getRecordCode));
                    months.put("ed", map.size());
                } else {
                    months.put("ed", 0);
                }
                byMonths.add(months);
            }
            if (trainAndCasePo.getType() == 4) {
                int count1 = leadingCadreService.count(Wrappers.<LeadingCadreEntity>lambdaQuery()
                        .like(LeadingCadreEntity::getCreateTime, date));
                writes.put("month", i);
                writes.put("all", count1);

                byMonths.add(writes);
                List<LeadingCadreEntity> leadingCadreEntities = leadingCadreService.list(Wrappers.<LeadingCadreEntity>lambdaQuery()
                        .like(LeadingCadreEntity::getCreateTime, date));
                if (CollUtil.isNotEmpty(leadingCadreEntities)) {
                    Set<String> writeCodes = leadingCadreEntities.stream().map(LeadingCadreEntity::getWriteCode).collect(Collectors.toSet());
                    List<MessageReceive> messageReceives = messageReceiveService.list(Wrappers.<MessageReceive>lambdaQuery()
                            .in(MessageReceive::getMessageCode, writeCodes)
                            .like(MessageReceive::getCreateTime, date));
                    if (CollUtil.isNotEmpty(messageReceives)) {
                        Map<String, List<MessageReceive>> map = messageReceives.stream().collect(Collectors.groupingBy(MessageReceive::getMessageCode));
                        writes.put("ed", map.size());
                    } else {
                        writes.put("ed", 0);
                    }
                } else {
                    writes.put("ed", 0);
                }

            }

        }
        return byMonths;
    }

    @Override
    public Page<HashMap<String, Object>> reviewAndTraining(ReviewAndTrainingPo reviewAndTrainingPo) {
        Page page = new Page(reviewAndTrainingPo.getCurrent(), reviewAndTrainingPo.getSize());
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        return this.baseMapper.reviewAndTraining(page, reviewAndTrainingPo, user.getUserCode());
    }

    @Override
    public List<HashMap<String, Object>> trainingArchivesPlanStatistics() {
        return this.baseMapper.trainingArchivesPlanStatistics();
    }

    @Override
    public List<TrainPlanVo> trainPlanList() {
        List<TrainPlanVo> trainPlanVos = new LinkedList<>();
        List<TrainPlan> list = this.list(new QueryWrapper<TrainPlan>().eq("STATUS", 2).orderByDesc("CREATE_TIME"));
        List<UserVo> personMap = this.baseMapper.getPersonMap();
        Map<String, String> map = personMap.stream().collect(Collectors.toMap(UserVo::getUserCode, UserVo::getUserName, (k1, k2) -> k1));
        List<DeptVo> dept = this.baseMapper.getDept();
        Map<String, String> deptMap = dept.stream().collect(Collectors.toMap(DeptVo::getDeptCode, DeptVo::getDeptName, (k1, k2) -> k1));
        if (list != null && list.size() > 0) {
            //处理执行人和处理目标对象
            list.stream().forEach(a -> {
                TrainPlanVo trainPlanVo = new TrainPlanVo();
                BeanUtils.copyProperties(a, trainPlanVo);
                String name = "";
                String code = "";
                JSONArray jsonArray = JSONObject.parseArray(a.getExecutor());
                if (!jsonArray.isEmpty()) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        String s = map.get(jsonArray.get(i));
                        name += s;
                        code += jsonArray.get(i);
                        if (i < jsonArray.size() - 1) {
                            name += ",";
                            code += ",";
                        }
                    }
                }
                trainPlanVo.setExecutor(name);
                trainPlanVo.setExecutorCode(code);
                //  处理目标对象
                String deptName = "";
                String deptCode = "";
                JSONArray deptArray = JSONObject.parseArray(a.getTargetItem());
                if (!deptArray.isEmpty()) {
                    for (int i = 0; i < deptArray.size(); i++) {
                        String s = deptMap.get(deptArray.get(i));
                        deptName += s;
                        deptCode += deptArray.get(i);
                        if (i < deptArray.size() - 1) {
                            deptName += ",";
                            deptCode += ",";
                        }
                    }
                }
                trainPlanVo.setTargetItemName(deptName);
                trainPlanVo.setTargetItem(deptCode);
                trainPlanVos.add(trainPlanVo);
            });
        }
        return trainPlanVos;
    }


    @Override
    @Transactional
    public boolean planExcel(MultipartFile file) {
        boolean isOk = false;
        List<PlanExcelVo> list = null;
        try {
            list = ExcelUtils.importExcel(file, PlanExcelVo.class);
            list = list.stream().filter(i -> i.getTrainType() != null).collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        Set<String> deptNames = list.stream().map(PlanExcelVo::getTargetItem).filter(Objects::nonNull).collect(Collectors.toSet());
        Set<String> userNames = list.stream().map(PlanExcelVo::getExecutor).filter(Objects::nonNull).collect(Collectors.toSet());
        Map<String, DeptInfoVos> map = new HashMap<>();
        Map<String, DeptInfoVos> hashMap = new HashMap<>();
        if (CollUtil.isNotEmpty(deptNames)) {
            List<DeptInfoVos> deptInfoVos = trainExamMapper.deptInfo(deptNames);
            if (deptNames.size() != deptInfoVos.size()) {
                Set<String> deptItems = deptInfoVos.stream().map(DeptInfoVos::getDeptName).collect(Collectors.toSet());
                deptNames.removeAll(deptItems);
                StringBuilder stringBuilder = new StringBuilder();
                for (String deptName : deptNames) {
                    stringBuilder.append(deptName).append("、");
                }
                String aaa = "目标对象填写不正确：";
                throw new BusinessException("10086", aaa + stringBuilder);
            }
            map = deptInfoVos.stream().collect(Collectors.toMap(DeptInfoVos::getDeptName, Function.identity()));
        }
        if (CollUtil.isNotEmpty(userNames)) {
            List<DeptInfoVos> deptInfoVos = this.getBaseMapper().userInfo(userNames);
            if (userNames.size() != deptInfoVos.size()) {
                Set<String> deptItems = deptInfoVos.stream().map(DeptInfoVos::getUserName).collect(Collectors.toSet());
                userNames.removeAll(deptItems);
                StringBuilder stringBuilder = new StringBuilder();
                for (String deptName : userNames) {
                    stringBuilder.append(deptName).append("、");
                }
                String aaa = "执行人填写不正确：";
                throw new BusinessException("10086", aaa + stringBuilder);
            }
            hashMap = deptInfoVos.stream().collect(Collectors.toMap(DeptInfoVos::getUserName, Function.identity()));
        }

        for (PlanExcelVo planExcelVo : list) {
            if (StrUtil.isNotBlank(planExcelVo.getTargetItem()) && map.containsKey(planExcelVo.getTargetItem())) {
                DeptInfoVos deptInfoVos = map.get(planExcelVo.getTargetItem());
                String deptCode = deptInfoVos.getDeptCode();
                List<String> depts = new ArrayList<>();
                depts.add(deptCode);
                planExcelVo.setTargetItem(JSON.toJSONString(depts));
            }
            if (StrUtil.isNotBlank(planExcelVo.getExecutor()) && hashMap.containsKey(planExcelVo.getExecutor())) {
                DeptInfoVos deptInfoVos = hashMap.get(planExcelVo.getExecutor());
                List<String> users = new ArrayList<>();
                String userCode = deptInfoVos.getUserCode();
                users.add(userCode);
                planExcelVo.setExecutor(JSON.toJSONString(users));
            }

            TrainPlanAddOrEditPo trainPlanAddOrEditPo = BeanUtil.copyProperties(planExcelVo, TrainPlanAddOrEditPo.class);
            List<TrainClass> trainClasses = new ArrayList<>();
            TrainClass trainClass = new TrainClass();
            trainClass.setTargetItem(planExcelVo.getTargetItem());
            trainClass.setExecutor(planExcelVo.getExecutor());
            trainClasses.add(trainClass);
            trainPlanAddOrEditPo.setTrainClass(trainClasses);
            isOk = this.add(trainPlanAddOrEditPo);
        }
        return isOk;
    }
}
